package com.example.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.utils.HttpUtils;
import com.example.gulimall.member.entity.MemberLevelEntity;
import com.example.gulimall.member.exception.PhoneExistException;
import com.example.gulimall.member.exception.UserNameExistException;
import com.example.gulimall.member.vo.MemberRegistVo;
import com.example.gulimall.member.vo.MemberUserLoginVo;
import com.example.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.member.dao.MemberDao;
import com.example.gulimall.member.entity.MemberEntity;
import com.example.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelServiceImpl memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo registVo) {

        MemberEntity memberEntity=new MemberEntity();
        //查询会员等级，刚注册默认普通会员，去会员等级表查询
        MemberLevelEntity default_status = memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));

        memberEntity.setLevelId(default_status.getId());
        //检查用户名和手机号是否唯一,为了controler能够感知到用户名存在，我们这里使用异常机制感知，如果已经存在就往上抛异常
        int mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", registVo.getPhone()));
       if (mobile>0){
           // 手机号已存在，向上抛出异常信息
           throw new PhoneExistException();
       }
        int userName = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", registVo.getUserName()));
        if (userName>0){
            // 用户名已存在，向上抛出异常信息
            throw new UserNameExistException();
        }
        memberEntity.setMobile(registVo.getPhone());
        memberEntity.setUsername(registVo.getUserName());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        //md5盐值加密，这个盐是在随机位置加的，并且同一个字符串每次加密结果都不一样，但是使用matches还是能比较出来，
        // 加强抗撞库攻击加密
        String encode = bCryptPasswordEncoder.encode(registVo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setNickname(registVo.getUserName());
        // 拿明文和密文相匹配，匹配成功会返回true,不成功false
        //boolean matches = bCryptPasswordEncoder.matches(registVo.getPassword(), encode);
        baseMapper.insert(memberEntity);
    }

    @Override
    public MemberEntity login(MemberUserLoginVo vo) {

        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", vo.getLoginacct())
                .or().eq("nickname", vo.getLoginacct())
                .or().eq("mobile", vo.getLoginacct())
                .or().eq("email", vo.getLoginacct()));
        if (memberEntity==null){
            //登录失败
            return  null;
        }else {
            //获取到数据库里的password
            String password1 = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //进行密码匹配
            boolean matches = passwordEncoder.matches(vo.getPassword(), password1);
            if (matches) {
                //登录成功
                return memberEntity;
            }
        }
        return  null;
    }

    /**
     * 社交登录
     * @param vo
     * @return
     */
    @Value("${geteehost}")
    private String geteehost;
    @Override
    public MemberEntity login(SocialUser vo) throws Exception {
        //登录，注册合并的逻辑
        //String uid = vo.getUid();
        //判断当前社交用户是否已经在我们系统登陆过
        String name="";
        String email="";
        String uid="";
        try {
            //查询当前社交用户的社交信息
            Map<String,String> map=new HashMap<>();
            map.put("access_token",vo.getAccess_token());
            HttpResponse response = HttpUtils.doGet(geteehost, "/api/v5/user", "get", new HashMap<String, String>(), map);
            if (response.getStatusLine().getStatusCode()==200){
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                uid=jsonObject.get("id").toString();
                 name = jsonObject.get("name").toString();
                 email = jsonObject.get("email").toString();



            }
        }catch (Exception e){

        }

        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid",uid));
        if (memberEntity!=null){
            //这个用户已经注册,更新token
           memberEntity.setAccessToken(vo.getAccess_token());
           memberEntity.setExpiresIn(vo.getExpires_in());
           baseMapper.updateById(memberEntity);
           return memberEntity;
        }else {
            //用社交用户第一次登录我们的系统，需要给系统注册账号
            MemberEntity regist = new MemberEntity();


            regist.setNickname(name);
            regist.setEmail(email);
            regist.setSocialUid(uid);
            regist.setAccessToken(vo.getAccess_token());
            regist.setExpiresIn(vo.getExpires_in());
            baseMapper.insert(regist);
            return  regist;
        }


    }

}